<template>
  <a-modal
    :visible="visible"
    title="任务复核"
    :width="1200"
    :footer="false"
    @cancel="onCancel"
    @update:visible="onUpdateVisible"
  >
    <a-form ref="formRef" :model="localForm" layout="vertical">
      <!-- 任务基本信息表单 -->
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="督办来源">
            <a-input v-model="localForm.source" disabled />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="问题类型">
            <a-input v-model="localForm.problemType" disabled />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="督察要求">
            <a-input v-model="localForm.requirements" disabled />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="领导批示">
            <a-checkbox v-model="localForm.leaderInstruction" style="margin-right: 24px; white-space: nowrap" disabled>
              批示
            </a-checkbox>
            <template v-if="localForm.leaderInstruction">
              <a-input v-model="localForm.leaderRemark" disabled style="width: 180px; margin-left: 12px" />
              <label style="margin-right: 8px; min-width: 70px">相关文件</label>
              <a-upload :file-list="localForm.leaderFiles" disabled />
            </template>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="整改单位">
            <a-input v-model="rfGroupNames" disabled />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="整改人员">
            <a-input v-model="rfUserNames" disabled />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="整改期限">
            <a-input v-model="rfDateDisplay" disabled />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="审核人">
            <a-input v-model="localForm.auditorName" disabled />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="备注">
            <a-input v-model="localForm.remark" disabled />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="相关附件">
            <a-upload :file-list="localForm.attachments" disabled />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="填报单位">
            <a-input v-model="localForm.reportDeptName" disabled />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="填报人">
            <a-input v-model="localForm.reportUser" disabled />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <div style="margin-top: 32px">
      <div class="form-section-title" style="margin: 24px 0 8px 0; font-weight: bold">整改单位反馈</div>
      <a-tabs v-model:active-key="activeTab">
        <a-tab-pane v-for="tab in tabList" :key="tab.rfUnit" :title="getTabTitle(tab)">
          <div>
            <div v-for="problem in tab.problems" :key="problem.problemId" style="margin-bottom: 24px">
              <a-card :bordered="true" style="margin-bottom: 8px; position: relative">
                <div style="margin-bottom: 12px">
                  <b>问题描述：</b>
                  <a-typography-paragraph :ellipsis="false" class="problem-desc-bg">
                    {{ problem.problemDesc }}
                  </a-typography-paragraph>
                </div>
                <div style="margin-bottom: 12px">
                  <b>核实情况：</b>
                  <a-typography-paragraph :ellipsis="false" class="problem-desc-bg">
                    {{ problem.checkMessage }}
                  </a-typography-paragraph>
                </div>
                <div style="margin-bottom: 12px">
                  <b>整改措施：</b>
                  <a-typography-paragraph :ellipsis="false" class="problem-desc-bg">
                    {{ problem.rfMeasures }}
                  </a-typography-paragraph>
                </div>
                <div style="margin-bottom: 12px">
                  <b>整改人：</b>
                  <span class="problem-desc-bg">{{ problem.rfUserName }}</span>
                </div>
                <div v-if="problem.status === 'pendingReview'">
                  <a-form-item label="审批意见">
                    <a-textarea
                      v-model="rejectMsg"
                      placeholder="请输入审批意见"
                      :auto-size="{ minRows: 2, maxRows: 4 }"
                    />
                  </a-form-item>
                </div>
                <div
                  v-if="problem.status && problem.status !== 'pendingReview'"
                  class="problem-status-stamp"
                  :style="statusStampStyle(problem.status)"
                >
                  {{ statusText(problem.status) }}
                </div>
                <div style="text-align: right; margin-top: 16px" v-if="problem.status === 'pendingReview'">
                  <a-button @click="onConfirm(problem)" type="primary" style="margin-right: 8px">复核通过</a-button>
                  <a-button @click="onReject(problem)" type="outline" status="danger">驳回</a-button>
                </div>
              </a-card>
            </div>
          </div>
        </a-tab-pane>
      </a-tabs>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
  import { ref, watch, computed, reactive } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import { getProblemReview, processReview } from '@/api/problem';
  import { getUserNameByIds } from '@/api/user';
  import { getGroupNameByIds } from '@/api/group';

  const props = defineProps({
    visible: Boolean,
    form: Object,
    taskId: [String, Number]
  });
  const emits = defineEmits(['update:visible', 'refresh']);
  const localForm = ref<any>({});
  const formRef = ref();
  const rfUserNames = ref('');
  const rfGroupNames = ref('');
  const activeTab = ref('');
  const tabList = ref<any[]>([]);
  const rejectMsg = ref('');

  // 计算属性
  const rfDateDisplay = computed(() => {
    if (!localForm.value?.rfStartDate || !localForm.value?.rfEndDate) return '';
    const d1 = new Date(localForm.value.rfStartDate);
    const d2 = new Date(localForm.value.rfEndDate);
    return `${d1.getFullYear()}年${String(d1.getMonth() + 1).padStart(2, '0')}月${String(d1.getDate()).padStart(2, '0')}日 - ${d2.getFullYear()}年${String(d2.getMonth() + 1).padStart(2, '0')}月${String(d2.getDate()).padStart(2, '0')}日`;
  });

  // 新增：tab标题显示逻辑
  function getTabTitle(tab: any) {
    const allReviewed = tab.problems.every((p: any) => p.status === 'reviewed');
    const nonePending = tab.problems.every((p: any) => p.status !== 'pendingReview');
    console.log('nonePending', `${tab.rfUnitName}（复核通过）`);
    if (allReviewed) {
      return `${tab.rfUnitName}（复核通过）`;
    } else if (nonePending) {
      return `${tab.rfUnitName}（已复核）`;
    }
    return tab.rfUnitName;
  }

  watch(
    () => props.form,
    val => {
      if (val && Object.keys(val).length) {
        localForm.value = { ...val };
      } else {
        localForm.value = {};
      }
    },
    { immediate: true, deep: true }
  );

  watch(
    () => props.visible,
    async v => {
      if (v && props.taskId) {
        try {
          const res = await getProblemReview(props.taskId);
          if (res && res.code === 200 && Array.isArray(res.data)) {
            // 按rfUnit分组
            const groupMap = new Map();
            res.data.forEach(item => {
              if (!groupMap.has(item.rfUnit)) {
                groupMap.set(item.rfUnit, {
                  rfUnit: item.rfUnit,
                  rfUnitName: item.rfUnitName,
                  status: item.status,
                  problems: []
                });
              }
              groupMap.get(item.rfUnit).problems.push(item);
            });
            tabList.value = Array.from(groupMap.values());
            if (tabList.value.length) {
              activeTab.value = String(tabList.value[0].rfUnit);
              // 默认展开所有tab
              tabList.value.forEach(tab => {
                // collapsedTabs[tab.rfUnit] = false; // This line is removed
              });
            }
          } else {
            tabList.value = [];
          }
        } catch (e) {
          Message.error('获取反馈信息失败');
          tabList.value = [];
        }
      }
    },
    { immediate: true }
  );

  // 监听整改人员变化
  watch(
    () => localForm.value.rfUsers,
    async newVal => {
      if (newVal) {
        const ids = typeof newVal === 'string' ? newVal.split(',') : newVal;
        try {
          const res = await getUserNameByIds(ids);
          if (Array.isArray(res.data)) {
            const names = res.data.map(item => item.name || item).filter(name => name);
            rfUserNames.value = names.join('，');
          } else {
            rfUserNames.value = '';
          }
        } catch (e) {
          rfUserNames.value = '';
        }
      } else {
        rfUserNames.value = '';
      }
    },
    { immediate: true }
  );

  // 监听整改单位变化
  watch(
    () => localForm.value.rfUnits,
    async newVal => {
      if (newVal) {
        const ids = typeof newVal === 'string' ? newVal.split(',') : newVal;
        try {
          const res = await getGroupNameByIds(ids);
          if (Array.isArray(res.data)) {
            const names = res.data.map(item => item.groupName || item).filter(name => name);
            rfGroupNames.value = names.join('，');
          } else {
            rfGroupNames.value = '';
          }
        } catch (e) {
          rfGroupNames.value = '';
        }
      } else {
        rfGroupNames.value = '';
      }
    },
    { immediate: true }
  );

  const problemColumns = [
    { title: '序号', dataIndex: 'index', width: 60 },
    { title: '问题描述', dataIndex: 'problemDesc', slotName: 'problemDesc' }
  ];

  const onCancel = () => {
    emits('update:visible', false);
  };
  function onUpdateVisible(v: boolean) {
    emits('update:visible', v);
  }
  async function onReject(problem) {
    if (!rejectMsg.value) {
      Message.error('请填写审批意见');
      return;
    }
    try {
      await processReview({
        taskId: props.taskId,
        problemId: problem.problemId,
        rfUser: problem.rfUser,
        review: false,
        msg: rejectMsg.value
      });
      Message.success('已驳回');
      problem.status = 'reject';
      emits('refresh');
    } catch (e) {
      Message.error('提交失败');
    }
  }

  async function onConfirm(problem) {
    try {
      const res = await processReview({
        taskId: props.taskId,
        problemId: problem.problemId,
        rfUser: problem.rfUser,
        review: true,
        msg: ''
      });
      if (res && res.data === 'finish') {
        emits('update:visible', false);
        emits('refresh');
        return;
      }
      Message.success('复核通过');
      problem.status = 'reviewed';
      emits('refresh');
    } catch (e) {
      Message.error('提交失败');
    }
  }

  function statusText(status: string) {
    switch (status) {
      case 'reviewed':
        return '已复核';
      case 'pendingReview':
        return '待复核';
      case 'reject':
        return '已驳回';
      default:
        return status;
    }
  }

  function statusStampStyle(status: string) {
    if (status === 'reject') {
      return { background: 'rgba(255, 77, 79, 0.85)' };
    } else if (status === 'reviewed') {
      return { background: 'rgba(24, 144, 255, 0.85)' };
    }
    return {};
  }
</script>

<style scoped>
  .problem-status-stamp {
    position: absolute;
    bottom: 16px;
    right: 16px;
    z-index: 10;
    color: #fff;
    font-weight: bold;
    font-size: 18px;
    padding: 6px 24px;
    border-radius: 8px;
    transform: rotate(-20deg);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    pointer-events: none;
    user-select: none;
    letter-spacing: 2px;
    text-align: center;
  }
  .problem-desc-bg {
    padding: 8px;
    border-radius: 4px;
    background: var(--problem-desc-bg, #f5f5f5); /* 浅色模式下为浅灰色 */
    color: var(--problem-desc-text, #222); /* 浅色模式下为深色文字 */
    margin: 0;
    white-space: pre-wrap;
    display: inline-block;
    transition:
      background 0.2s,
      color 0.2s;
  }
  body[data-theme='dark'] .problem-desc-bg,
  html[data-theme='dark'] .problem-desc-bg {
    background: var(--problem-desc-bg-dark, #232324); /* 深色模式下为深灰色 */
    color: var(--problem-desc-text-dark, #fff); /* 深色模式下为白色文字 */
  }
</style>
